<template>
    <ul class="list">
      <li class="item" v-for="key of letters" :key="key" @click="handleLetterClick"
                                                                @touchstart="handleTouchStart"
                                                                @touchmove="handleTouchMove"
                                                                @touchend="handleTouchEnd"
                                                                :ref="key"
                                                                >
        {{key}}
      </li>
    </ul>
</template>

<script>
  export default {
    name: 'CityAlphabet',
    props:{
      cities: Object
    },
    data(){
      return {
        touchStatus: false,
        startY: 0,
        timer: null,
      }
    },
    updated() {
      this.startY = this.$refs['A'][0].offsetTop;
    },
    //计算属性
    computed: {
      letters () {
        const letters = [];
        for (let i in this.cities){
          letters.push(i);
        }
        return letters;
      }
    },
    methods: {
      handleLetterClick(e){
        //往父组件传值,给父组件触发一个change事件
        this.$emit('change', e.target.innerText)
      },
      handleTouchStart(){
        this.touchStatus = true;
      },
      handleTouchMove(e){
        if (this.touchStatus){
          if (this.timer != null){
            clearTimeout(this.timer);
          }

          this.timer = setTimeout(() => {
            //79是和上面的高度
            const touchY = e.touches[0].clientY - 79;
            const index = Math.floor((touchY - this.startY) / 20);
            if (index >= 0 && index < this.letters.length){
              this.$emit('change', this.letters[index]);
            }
          }, 6);
        }
      },
      handleTouchEnd(){
        this.touchStatus = false;
      },

    }
  }
</script>

<style scoped lang="stylus">

  @import "~styles/varibles.styl"

  .list
    position: absolute
    top: 1.58rem
    right: 0
    bottom: 0
    width: .4rem
    display: flex
    flex-direction: column
    justify-content: center
    .item
      line-height: .4rem
      color: $bgColor
      text-align: center

</style>
